package com.vilynn.learning.blockingqueue;

/**
 * @author weilin.wang
 */
public class MyBlockingQueue {
    private Object[] items;
    private int index;

    public Object[] getItems() {
        return items;
    }

    private MyBlockingQueue(){

    }
    public MyBlockingQueue(int size){
        items = new Object[size];
    }

    public void add(Object object){
        if(index == items.length){
            throw new IndexOutOfBoundsException("队列满了");
        }else{
            items[index++] = object;
        }
    }
    public boolean offer(Object object){
        if(index == items.length){
            return false;
        }else{
            items[index++] = object;
            return true;
        }
    }
    public void put(Object object) throws InterruptedException {
        if(index == items.length){
            Thread.sleep(1000L);
            put(object);
        }else{
            items[index++] = object;
        }
    }

    public Object poll(int seconds) throws InterruptedException {
        long time = System.currentTimeMillis() + Long.valueOf(seconds) * 1000;
        Object res = null;
        do{
            if(index > 0){
                res = items[0];
                index--;
                moveArray(items);
                break;
            }
            Thread.sleep(1000L);
        } while (System.currentTimeMillis() > time);
        return res;
    }

    private void moveArray(Object[] items) {
        for (int i = 0; i < items.length; i++) {
            if(i == items.length-1){
                items[i] = null;
                return;
            }
            items[i] = items[i+1];
            items[i+1] = null;
            if(items[i] == null){
                break;
            }
        }
    }

    public Object take() throws InterruptedException {
        Object res = null;
        do{
            if(index > 0){
                res = items[0];
//                items =
                moveArray(items);
                break;
            }
            Thread.sleep(1000L);
        } while (true);
        return res;
    }

}
